package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class HuanXinTokenService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    public static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String getToken() {

        // 先让其命中缓存,以分散后台压力
        String accessToken = redisTemplate.opsForValue().get(REDIS_KEY);
        if (StringUtils.isNotEmpty(accessToken)){
            return accessToken;
        }

        String targetUrl = this.huanXinConfig.getUrl() + this.huanXinConfig.getOrgName() + "/"
                + this.huanXinConfig.getAppName() + "/token";

        Map<String, String> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());

        //请求环信接口
        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(targetUrl, param, String.class);

        if (responseEntity.getStatusCodeValue() != 200) {
            return null;
        }

        try {
            JsonNode jsonNode = MAPPER.readTree(responseEntity.getBody());
            accessToken = jsonNode.get("access_token").asText();// 获取token
//            long expriesIn = jsonNode.get("expries_in").asLong(); // 获取过期时间

            if (StringUtils.isNotEmpty(accessToken)) {
                // 与视频中不同,已经写死,此处为5天过期
                redisTemplate.opsForValue().set(REDIS_KEY, accessToken,Duration.ofDays(5));
                return accessToken;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}